package com.heima.wemedia.controller.v1;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/news")
public class WmNewsController {
    @Autowired
    private WmNewsService wmNewsService;

    @PostMapping("/list")
    public ResponseResult findAll(@RequestBody WmNewsPageReqDto dto) {

        return wmNewsService.findAll(dto);
    }
    @PostMapping("/submit")
    public ResponseResult submitNews(@RequestBody WmNewsDto dto){
        return wmNewsService.submitNews(dto);
    }
    /**
     * 查看文章详情
     */
    @GetMapping("/one/{id}")
    public ResponseResult selectAllById(@PathVariable("id") Integer id ){
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = wmNewsService.getById(id);
        if(StringUtils.isEmpty(wmNews)){
            return ResponseResult.errorResult(200,"文章不存在");
        }
        return ResponseResult.okResult(wmNews);
    }
    /**
     * 文章删除
     * @param id
     * @return
     */
    @GetMapping("/del_news/{id}")
    public ResponseResult deleteNewSById(@PathVariable("id")Integer id){
        if(id==null){
            return ResponseResult.errorResult(501,"文章id不可缺少");
        }
        WmNews byId = wmNewsService.getById(id);
        if(StringUtils.isEmpty(byId)){
            return ResponseResult.errorResult(1002,"文章不存在");
        }
        if(byId.getStatus()==9){
            return ResponseResult.errorResult(501,"文章已经发布，不能删除");
        }
        wmNewsService.removeById(id);
        return ResponseResult.okResult(200,"操作成功");
    }
    /**
     * 文章上下架
     */
    @PostMapping("/down_or_up")
    public ResponseResult downOrUpAll(@RequestBody WmNewDto wmNewDto){
        if(StringUtils.isEmpty(wmNewDto)){
            return ResponseResult.errorResult(501,"文章id不可缺少");
        }
        Integer newDtoId = wmNewDto.getId();
        WmNews wmNews = wmNewsService.getById(newDtoId);
        if(StringUtils.isEmpty(wmNews)){
            return ResponseResult.errorResult(1002,"文章不存在");
        }
        if(wmNews.getStatus()<9){
            return ResponseResult.errorResult(501,"当前文章不是发布状态不能下架");
        }
        wmNews.setEnable(wmNewDto.getEnable());
        wmNewsService.updateById(wmNews);
        return ResponseResult.okResult(200,"操作成功");
    }
}